package climspace.client;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;

import climspace.ejb.WeatherStationBean;

public class CapaAnalystClient {

	private Context ctx;
	private WeatherStationBean svc;
	private String host = "localhost";

	public void setHost(String host) {
		this.host = host;
	}

	private Context getContext() throws Exception {
		if (ctx != null)
			return ctx;

		Properties props = new Properties();
		props.put(Context.PROVIDER_URL, "jnp://" + host + ":1099");
		props.put(Context.INITIAL_CONTEXT_FACTORY,
				"org.jnp.interfaces.NamingContextFactory");
		props.put(Context.URL_PKG_PREFIXES,
				"org.jboss.naming:org.jnp.interfaces");
		ctx = new InitialContext(props);

		return ctx;
	}

	private WeatherStationBean connectToService() throws Exception {
		if (svc != null)
			return svc;

		Context ctx = getContext();
		Object ref = ctx.lookup("WeatherStationBeanEJB/remote");
		svc = (WeatherStationBean) PortableRemoteObject.narrow(ref,
				WeatherStationBean.class);

		return svc;
	}

	public String getHistoricalWeatherData(String stationId,
			Date fromDate, Date toDate, String userName){
		String jobID = null;
		if (stationId == null)
			throw new RuntimeException("Missing StationId");
		
		try {
			 jobID = connectToService().getHistoricalWeatherData(stationId,
					fromDate,toDate, userName);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return jobID;
	}
	
	public String downloadDataFileByJobID(String jobID, String outFolder) {
		if (jobID == null || outFolder == null)
			throw new RuntimeException("Missing JobId or outFolder");
		String outFile = "";
		try {
			outFile = connectToService().downloadDataFileByJobID(jobID, outFolder);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return outFile;
	}
	
	public static void main(String[] args) {
		CapaAnalystClient capaAnalystClient = new CapaAnalystClient();
		try {
			String stationId = args[0];
			String fromDateString = args[1];
			String toDateString = args[2];
			String userName = args[3];
			SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
			Date fromDate = formatter.parse(fromDateString);
			Date toDate = formatter.parse(toDateString);
			
			capaAnalystClient.getHistoricalWeatherData(stationId , fromDate, toDate, userName);
			
			
			/*String jobID = "";
			String outFolder = "";
			String outFile = capaAnalystClient.downloadDataFileByJobID(jobID, outFolder);*/
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
}
